import { createSlice, type PayloadAction } from '@reduxjs/toolkit'
import type { Commodity } from '../../api/shops';



// 全局购物车状态（按商家分组）
export interface CartState {
  cartShop: Record<string, Commodity[]>; // { "商家ID1": [商品1, 商品2], "商家ID2": [商品3] }
}
const initialState: CartState = {
  cartShop: {}
}

const cartSlice = createSlice({
  name: 'cart',
  initialState,
  reducers: {
    
    addCartList: (state, action: PayloadAction<{ commodity: Commodity, shops_id: string }>) => {
      const { commodity, shops_id } = action.payload
      // 确保当前商家的购物车数组存在（不存在则初始化）
      if (!state.cartShop[shops_id]) {
        state.cartShop[shops_id] = [];
      }
      const shopCart = state.cartShop[shops_id]

      const index = shopCart.findIndex((item) => {
        return item._id === commodity._id
      })
      if (index === -1) {
        const comm = { ...commodity, count: 1 }
        shopCart.push(comm)

      } else {
        shopCart[index].count += 1
      }

    },
    disCartList: (state, action: PayloadAction<{ shops_id: string, commodity_id: string }>) => {
      const { commodity_id, shops_id } = action.payload
      if (!state.cartShop[shops_id]) {
        return
      }
      const shopCart = state.cartShop[shops_id]
      const index = shopCart.findIndex((item) => {
        return item._id === commodity_id
      })
      if (index === -1) {
        return
      } else {
        if (shopCart[index].count > 1) {
          shopCart[index].count -= 1
        } else {
          shopCart.splice(index, 1)
        }
      }

    },
    clearShopCartItem: (state, action: PayloadAction<{ shops_id: string }>) => {
      const { shops_id } = action.payload
      console.log('234')
      state.cartShop[shops_id] = []
    }
  }
})

export const { addCartList, disCartList, clearShopCartItem } = cartSlice.actions


export const cartReducer = cartSlice.reducer


